package com.java.zhuiyun.api.order.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.java.zhuiyun.api.alipay.common.AliPayConfig;
import com.java.zhuiyun.api.alipay.controller.AliPay;
import com.java.zhuiyun.api.front_desk_user.mapper.FrontDeskUserMapper;
import com.java.zhuiyun.api.memberShip_records.mapper.MemberShipMapper;
import com.java.zhuiyun.api.memberShip_records.service.MemberShipService;
import com.java.zhuiyun.api.order.entity.Orders;
import com.java.zhuiyun.api.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName AliPayController
 * @Description TODO
 * @Author WX
 * @Date 2023/8/23 9:29
 **/
@RestController
@RequestMapping("/alipayCoursePc")
@CrossOrigin
public class AliPayOrderController {

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AliPayConfig aliPayConfig;

    @Autowired
    private MemberShipService memberShipService;

    @Autowired
    private MemberShipMapper memberShipMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private FrontDeskUserMapper frontDeskUserMapper;

    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(Orders aliPay, HttpServletResponse httpResponse) throws Exception {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        // 2. 创建 Request并设置Request参数
        // 发送请求的 Request类
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        JSONObject bizContent = new JSONObject();
        // 我们自己生成的订单编号
        bizContent.set("out_trade_no", aliPay.getOrderNumber());
        // 订单的总金额
        bizContent.set("total_amount", aliPay.getPaymentPrice());
        // 支付的名称
        bizContent.set("subject", aliPay.getOrderName());
        // 固定配置
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());

        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

//    /*
//    * @Author WX
//    * @Description 支付宝回调
//    * @Date 2023/8/24 9:04
//    * @Return
//    * @param null
//    */
//    // 注意这里必须是POST接口
//    @PostMapping("/notify")
//    public String payNotify(HttpServletRequest request) throws Exception {
//        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
//            System.out.println("=========支付宝异步回调========");
//            Map<String, String> params = new HashMap<>();
//            Map<String, String[]> requestParams = request.getParameterMap();
//            for (String name : requestParams.keySet()) {
//                params.put(name, request.getParameter(name));
//                // System.out.println(name + " = " + request.getParameter(name));
//            }
//            String memberNumber = params.get("out_trade_no");
//            String createTime = params.get("gmt_payment");
//            String paymentCode = params.get("trade_no");
//            String sign = params.get("sign");
//            String content = AlipaySignature.getSignCheckContentV1(params);
//            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
//            // 支付宝验签
//            if (checkSignature) {
//                // 验签通过
//                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
//                // 查询订单
//                AliPay aliPay = memberShipMapper.selectOneShip(memberNumber);
//
//                // 修改订单支付状态
//                if (aliPay != null) {
//                    aliPay.setPaymentCode(paymentCode);
//                    aliPay.setCreateTime(new Date());
//                    aliPay.setPayment(1);
//                    memberShipService.updateById(aliPay);
//                }
//            }else {
//
//            }
//        }
//        return "success";
//    }
}
